﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Code.Models;
using Code.Commen;

namespace Code.BLL
{
    public class AddMoneyManage:ManageBase<AddMoneyDetail>
    {
        public int BuildPayOrder(Guid userid, double money, PayType paytype,out Guid orderid,string siteid = null)
        {
            int rs=-1;
            orderid = Guid.NewGuid();

            if (money <= 0)
                throw new ValidateException("在线充值:金额必须大于0");

            var item = new
            {
                ID=orderid,
                PayType=paytype.ToString(),
                Money=money,
                UserID=userid,
                SiteID=siteid
            };

            rs = base.Insert<PayDetail>(item);
            return rs;
        }

        public int CallBackPay(PayDetail pay)
        {
            int rs = -1;
            lock (obj)
            {
                var pay1 = base.Select<PayDetail, PayDetail>(s => s.FirstOrDefault(p => p.ID == pay.ID));
                if (pay1 == null)
                    throw new ValidateException("不存在该支付信息");
                if (pay1.Money != pay.Money)
                    throw new ValidateException("支付金额不正确");
                if (pay1.Result == (short)PayResult.Success)
                    return 0;
                string Remark = ((PayType)Enum.Parse(typeof(PayType), pay1.PayType)).GetName();

                if (pay1.PayType == PayType.ICBC_Manual.ToString())
                {
                    double tmp;
                    var ratio = CacheManage.OptionSite[Option_Site_Key.Site_Pay_ICBC_Manual_ChargeRatio].ToDouble(out tmp) ? tmp / 100 : null as double?;
                    var min = CacheManage.OptionSite[Option_Site_Key.Site_Pay_ICBC_Manual_MinCharge].ToDouble(out tmp) ? tmp : null as double?;
                    var max = CacheManage.OptionSite[Option_Site_Key.Site_Pay_ICBC_Manual_MaxCharge].ToDouble(out tmp) ? tmp : null as double?;
                    double? tmp2 = null;
                    if (ratio.HasValue)
                        tmp2 = (double)pay1.Money * ratio.Value;
                    if (min.HasValue)
                        tmp2 = Math.Max(tmp2 ?? (double)min.Value, min.Value);
                    if (ratio.HasValue && max.HasValue)
                        tmp2 = Math.Min(tmp2.Value, max.Value);
                    if (tmp2.HasValue)
                    {
                        string str = string.Format("(充值金额:{0:F2}元,费率{1:F2}元)", pay1.Money, tmp2);
                        Remark += str;
                        pay1.Money += (decimal)tmp2.Value;
                    }
                }

                base.BeginTransaction();
                base.Update<PayDetail>(new { Result = (short)PayResult.Success, SuccesTime = new SqlExpression("getdate()"), pay.PayID, pay.PayType, Remark = pay.Remark }, new { Result = (short)PayResult.WatingPay, pay1.ID });
                base.Insert<AddMoneyDetail>(new { UserID = pay1.UserID, Money = pay1.Money, Type = (short)AddMoneyType.OnlinePay, RefID = pay1.ID, Remark });
                base.Update<Account>(new { Balance = new OpteratorValue(Opterator.Add, pay1.Money), AddMoney = new OpteratorValue(Opterator.Add, pay1.Money) }, new { UserID = pay1.UserID });
                rs = base.ExecuteTransaction(3);
            }
            return rs;
        }

        /// <summary>
        /// 撤销等待支付的订单
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public int RevocationOrder(PayDetail pay)
        {
            
              int rs = -2;
              lock (obj)
              {
                  var pay1 = base.Select<PayDetail, PayDetail>(s => s.FirstOrDefault(p => p.ID == pay.ID));
                  if (pay1 == null)
                      throw new ValidateException("不存在该支付信息");
                  if (pay1.Money != pay.Money)
                      throw new ValidateException("支付金额不正确");
                  if (pay1.Result == (short)PayResult.Success)
                      return 0;
                  string Remark = ((PayType)Enum.Parse(typeof(PayType), pay1.PayType)).GetName();

                  if (pay1.PayType == PayType.ICBC_Manual.ToString())
                  {
                      double tmp;
                      var ratio = CacheManage.OptionSite[Option_Site_Key.Site_Pay_ICBC_Manual_ChargeRatio].ToDouble(out tmp) ? tmp / 100 : null as double?;
                      var min = CacheManage.OptionSite[Option_Site_Key.Site_Pay_ICBC_Manual_MinCharge].ToDouble(out tmp) ? tmp : null as double?;
                      var max = CacheManage.OptionSite[Option_Site_Key.Site_Pay_ICBC_Manual_MaxCharge].ToDouble(out tmp) ? tmp : null as double?;
                      double? tmp2 = null;
                      if (ratio.HasValue)
                          tmp2 = (double)pay1.Money * ratio.Value;
                      if (min.HasValue)
                          tmp2 = Math.Max(tmp2 ?? (double)min.Value, min.Value);
                      if (ratio.HasValue && max.HasValue)
                          tmp2 = Math.Min(tmp2.Value, max.Value);
                      if (tmp2.HasValue)
                      {
                          string str = string.Format("(充值金额:{0:F2}元,费率{1:F2}元)", pay1.Money, tmp2);
                          Remark += str;
                          pay1.Money += (decimal)tmp2.Value;
                      }
                  }

                 rs=base.Update<PayDetail>(new { Result = (short)PayResult.Cancel, SuccesTime = new SqlExpression("getdate()"), pay.PayID, pay.PayType, Remark = pay.Remark }, new { Result = (short)PayResult.WatingPay, pay1.ID });
              }
                return rs;
        }
        /// <summary>
        /// 撤销等待支付的订单
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public int CancelOrder(Guid? uid, long order)
        {
            if (uid.HasValue)
                return base.Update<PayDetail>(new { Result = (short)PayResult.Cancel }, new { Result = (short)PayResult.WatingPay, OrderID = order, UserID = uid });
            else
                return base.Update<PayDetail>(new { Result = (short)PayResult.Cancel }, new { Result = (short)PayResult.WatingPay, OrderID = order });
        }
        /// <summary>
        /// 后台手工充值
        /// </summary>
        public int AdminAddMoney(string userName, double money, Guid adminId)
        {
            int rs = 0;
            if (string.IsNullOrEmpty("userName"))
                throw new ValidateException("用户名不能为空", "userName");
            var user = base.Tables.Users.FirstOrDefault(p => p.LoginName == userName);
            if (user == null)
                throw new ValidateException("不存在该用户","userName");

            base.BeginTransaction();
            base.Insert(new { UserID = user.ID, Money = money, Type = (short)AddMoneyType.AdminAdd, RefID = adminId });
            base.Update<Account>(new { Balance = new OpteratorValue(Opterator.Add, money), AddMoney = new OpteratorValue(Opterator.Add, money) }, new { UserID=user.ID });
            rs = base.ExecuteTransaction(2);

            return rs;
        }


        /// <summary>
        /// 在线支付回调时用的线程锁
        /// </summary>
        private static object obj = new object();


    }
}
